/**
 * Copyright By Nanjing Fujitsu Nanda Software Technology Co., Ltd
 * 下午5:53:47
 * TriggerController.java
 * 
 */
package com.snda.game.legend.controller;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;
import org.quartz.Scheduler;
import org.quartz.SchedulerException;
import org.quartz.SimpleTrigger;
import org.quartz.Trigger;
import org.quartz.impl.StdScheduler;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.snda.game.legend.base.BaseController;

/**
 * @author qixb.fnst
 * 
 */
@Controller
public class TriggerController extends BaseController {
    /**
     * Logger for this class
     */
    private static final Logger logger = Logger
            .getLogger(TriggerController.class);

    @Resource
    private StdScheduler scheduler;

    @RequestMapping(value = { "/admin/triggers" }, method = RequestMethod.GET)
    public String trigger(Model model, HttpSession session)
            throws SchedulerException {
        if (!isLogin(session)) {
            return redirect("/admin");
        }
        List<TriggerStruct> triggers = new ArrayList<TriggerStruct>();
        // for (String groupName : scheduler.getTriggerGroupNames()) {
        // TriggerStruct triggerStruct = null;
        // String[] triggerNames = scheduler.getTriggerNames(groupName);
        // for (String triggerName : triggerNames) {
        // triggerStruct = new TriggerStruct();
        // triggerStruct.setTriggerGroup(groupName);
        // triggerStruct.setTriggerName(triggerName);
        // triggers.add(triggerStruct);
        // }
        // }
        String groupName = Scheduler.DEFAULT_GROUP;
        TriggerStruct triggerStruct = null;
        String[] triggerNames = scheduler.getTriggerNames(groupName);
        for (String triggerName : triggerNames) {
            triggerStruct = new TriggerStruct();
            triggerStruct.setTriggerGroup(groupName);
            triggerStruct.setTriggerName(triggerName);
            triggers.add(triggerStruct);
        }
        model.addAttribute("triggers", triggers);
        return "admin/trigger";
    }

    @RequestMapping(value = { "/admin/triggers/{triggerGroup}/{triggerName}/{operation}" })
    public String startTrigger(Model model, @PathVariable String triggerGroup,
            @PathVariable String triggerName, @PathVariable String operation,
            HttpSession session) throws SchedulerException {
        if (!isLogin(session)) {
            return redirect("/admin");
        }
        Trigger trigger = scheduler.getTrigger(triggerName, triggerGroup);
        if (trigger != null) {
            if (operation != null) {
                if (operation.equals("enable")) {
                    scheduler.resumeJob(trigger.getJobName(),
                            trigger.getJobGroup());
                } else if (operation.equals("disable")) {
                    scheduler.pauseJob(trigger.getJobName(),
                            trigger.getJobGroup());
                } else {
                    /*
                     * JobDetail jobDetail = scheduler.getJobDetail(
                     * trigger.getJobName(), trigger.getJobGroup()); Job job =
                     * (Job) jobDetail.getJobClass().newInstance();
                     */
                    scheduler.triggerJob(trigger.getJobName(),
                            trigger.getJobGroup());
                }
            }

        }
        return redirect("/admin/triggers");
    }

    @RequestMapping(value = { "/admin/triggers/{triggerGroup}/{triggerName}/changeInterval/{interval}" })
    public String changeInterval(Model model,
            @PathVariable String triggerGroup,
            @PathVariable String triggerName, @PathVariable String interval,
            HttpSession session) throws SchedulerException {
        if (!isLogin(session)) {
            return redirect("/admin");
        }
        Trigger trigger = scheduler.getTrigger(triggerName, triggerGroup);
        int intervalInt = 10;
        if (trigger != null) {
            if (interval != null) {
                try {
                    intervalInt = Integer.parseInt(interval);
                    if (intervalInt <= 0) {
                        throw new NumberFormatException("interval不可为负数！");
                    }
                } catch (NumberFormatException exception) {
                    exception.printStackTrace();
                    model.addAttribute("result", false);
                    return redirect("/trigger.do");
                }
                if (trigger != null && trigger instanceof SimpleTrigger) {
                    SimpleTrigger st = (SimpleTrigger) trigger;
                    st.setRepeatInterval(intervalInt * 60 * 1000);
                    st.setStartTime(new Date());
                    scheduler.rescheduleJob(triggerName, triggerGroup, trigger);
                }

            }

        }
        model.addAttribute("result", true);
        return redirect("/admin/trigger");
    }

    public static class TriggerStruct {
        /**
         * Logger for this class
         */
        private static final Logger logger = Logger
                .getLogger(TriggerStruct.class);

        private String triggerName;
        private String triggerGroup;

        public String getTriggerName() {
            return triggerName;
        }

        public void setTriggerName(String triggerName) {
            this.triggerName = triggerName;
        }

        public String getTriggerGroup() {
            return triggerGroup;
        }

        public void setTriggerGroup(String triggerGroup) {
            this.triggerGroup = triggerGroup;
        }
    }

}
